<?php
require_once 'Zend/Form/Decorator/Abstract.php';

/**
 * Decorator which is used in combination with Asirra
 * captcha adapter, and which renders necessary JS code
 * that will trigger Asirra challenge validation after
 * the form, in which Asirra captcha adapter is used,
 * is submitted.
 * This decorator will try to intercept submit event on
 * the parent form, using jQuery, served by Google's API.
 * Asirra_CheckIfHuman() function will then be triggered
 * in the event handler.
 *
 * @author Nikola Posa <posa.nikola@gmail.com>
 * @license http://opensource.org/licenses/gpl-3.0.html GNU General Public License
 */
class NP_Form_Decorator_Captcha_AsirraCheckIfHuman extends Zend_Form_Decorator_Abstract
{
    /**
     * Renders additional JS code for the Asirra captcha
     * implementation.
     *
     * @param string $content
     * @return string
     */
    public function render($content)
    {
        $element = $this->getElement();
        if (!method_exists($element, 'getCaptcha')) {
            return $content;
        }

        $captcha = $element->getCaptcha();
        if (!$captcha instanceof NP_Captcha_Asirra) {
            return $content;
        }

        $content .= '
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
if (typeof jQuery == \'undefined\') { //No jQuery? Include it.
	google.load("jquery", "1.4.2");
}

google.setOnLoadCallback(function() {
	var passThroughFormSubmit = false;
	var form = 	$(\'#' . NP_Captcha_Asirra::ASIRRA_TICKET_FIELD . '\').parents(\'form:first\');
	if (form) {
		$(form).submit(function(event) {
			if (passThroughFormSubmit) {
				return true;
			}
			
			event.preventDefault();
			
			Asirra_CheckIfHuman(HumanCheckComplete);
		});
		
		function HumanCheckComplete(isHuman)
		{
			passThroughFormSubmit = true;
			$(form).submit();
		}
	}
});
</script>';
        
        return $content;
    }
}